package com.proxy.server.frontend.handler.request.proxy;

import com.proxy.common.constant.ErrorCodeType;
import com.proxy.common.constant.IsolationType;
import com.proxy.common.packet.BinaryPacket;
import com.proxy.common.packet.ErrorPacket;
import com.proxy.common.packet.OkPacket;
import com.proxy.parser.result.SetTransactionResult;
import com.proxy.router.SQLRouteResult;
import com.proxy.server.frontend.FrontendConnection;
import com.proxy.server.frontend.session.Session;

import java.nio.charset.Charset;

/**
 * Created by liufish on 16/8/8.
 */
public class SetTransactionProxy {



    public static void doProxy(BinaryPacket bin, Session session, SQLRouteResult result){

        FrontendConnection connection = session.getFrontendConnection();

        SetTransactionResult setTransactionResult  = (SetTransactionResult)result.getExtra();

        String level = setTransactionResult.getLevel();
        if(level.equalsIgnoreCase("READ UNCOMMITTED")){
            connection.setTxIsolation(IsolationType.READ_UNCOMMITTED);
            connection.write(OkPacket.getOk(++bin.packetId));
            return;
        }else if(level.equalsIgnoreCase("READ COMMITTED")){
            connection.setTxIsolation(IsolationType.READ_COMMITTED);
            connection.write(OkPacket.getOk(++bin.packetId));
            return;
        }else if(level.equalsIgnoreCase("REPEATABLE READ")){
            connection.setTxIsolation(IsolationType.REPEATED_READ);
            connection.write(OkPacket.getOk(++bin.packetId));
            return;
        }else if(level.equalsIgnoreCase("SERIALIZABLE")){
            connection.setTxIsolation(IsolationType.SERIALIZABLE);
            connection.write(OkPacket.getOk(++bin.packetId));
            return;
        }else {
            ErrorPacket error = new ErrorPacket();
            error.packetId =  ++ bin.packetId;
            error.errNo = ErrorCodeType.ER_UNKNOWN_CHARACTER_SET;
            error.message = "Unknown TxIsolation!".getBytes(Charset.forName(connection.getCharset()));
            connection.write(error);
        }



    }
}
